package com.example.admindatasource;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class test {
    public static void main(String[] args) {
        Menu menu = new Menu(1L,"个人中心",0L,2);

        Menu menu2 = new Menu(3L,"个人信息",1L,2);
        Menu menu1 = new Menu(2L,"用户管理",1L,2);
        Menu menu6 = new Menu(7L,"XXXX管理",2L,1);

        Menu menu3 = new Menu(4L,"头像相关",3L,1);
        Menu menu4 = new Menu(5L,"邮箱设置",3L,1);
        Menu menu5 = new Menu(6L,"订阅设置",3L,1);


        List<Menu> list = new ArrayList<>();
        list.add(menu);
        list.add(menu1);
        list.add(menu2);
        list.add(menu3);
        list.add(menu4);
        list.add(menu5);
        list.add(menu6);

        // 获取父集的集合
        List<Menu> topList = list.stream().filter(i -> i.getPid() == 0).collect(Collectors.toList());

        for (Menu men : topList) {
//            men.setOption(setOption(men,list));
            men.setMenus(getChild(men.getId(),list));
        }


        topList.forEach(System.out::println);
    }


    private static List<Menu> getChild(Long id, List<Menu> rootMenu) {
        // 子菜单
        List<Menu> childList = new ArrayList<>();
        for (Menu menu : rootMenu) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (menu.getPid() != 0) {
                if (menu.getPid().equals(id)) {
                    childList.add(menu);
                }
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (Menu menu : childList) {
            menu.setMenus(getChild(menu.getId(), rootMenu));
        } // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }


    private static Integer setOption(Menu menu, List<Menu> rootMenu){
        if (menu.getOption() == 1){
            return 1;
        }
        List<Menu> topList = rootMenu.stream().filter(i -> i.getPid().equals(menu.getId())).collect(Collectors.toList());
        if (topList.size() == 0){
            return 2;
        }
        boolean isok = true;
        for (Menu menu1 : topList) {
            menu1.setOption(setOption(menu1, rootMenu));
            if (menu1.getOption() ==2){
                isok = false;
            }
        }
        return isok?1 : 2;
    }
}
